import { defineStore } from 'pinia'
import { authAPI } from '@/api/auth'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    user: null,
    isLoggedIn: !!localStorage.getItem('token'),
  }),

  getters: {
    isAdmin: (state) => state.user?.role === 'admin',
    isAuthenticated: (state) => !!state.token && !!state.user,
  },

  actions: {
    async login(credentials) {
      try {
        const response = await authAPI.login(credentials)
        if (response.success) {
          this.token = response.data.token
          this.user = response.data.user
          this.isLoggedIn = true
          localStorage.setItem('token', this.token)
          return { success: true, message: response.message }
        }
        return { success: false, message: response.message }
      } catch (error) {
        return { success: false, message: error.response?.data?.message || '登录失败' }
      }
    },

    async register(userData) {
      try {
        const response = await authAPI.register(userData)
        return { success: response.success, message: response.message }
      } catch (error) {
        return { success: false, message: error.response?.data?.message || '注册失败' }
      }
    },

    async fetchUserInfo() {
      try {
        const response = await authAPI.getUserInfo()
        if (response.success) {
          this.user = response.data
          this.isLoggedIn = true
          return { success: true, data: response.data }
        }
        return { success: false, message: response.message }
      } catch (error) {
        this.logout()
        return { success: false, message: '获取用户信息失败' }
      }
    },

    async logout() {
      try {
        await authAPI.logout()
      } finally {
        this.token = ''
        this.user = null
        this.isLoggedIn = false
        localStorage.removeItem('token')
      }
    },

    setUser(userData) {
      this.user = userData
    },
  },
})